<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>防抖&节流</title>
  </head>
  <body>
    <button onclick="fn('Hello')">click</button>
    <script>
      function debounce (fn, delay) {
        let timer = null
        return function () {
          clearTimeout(timer)
          timer = setTimeout(() => {
            fn.apply(this, arguments)
          }, delay)
        }
      }

      function throttle (fn, delay) {
        let canRun = true
        return function () {
          if (canRun) {
            canRun = false
            setTimeout(() => {
              fn.apply(this, arguments)
              canRun = true
            }, delay)
          }
        }
      }

      let fn = throttle(function (str) {
        console.log(str)
      }, 1000)
    </script>
  </body>
</html>
